const crypto = require('crypto');
const axios = require('axios');

/**
 * {"msg":"success","code":"0","data":{"token":"c070800f-f50f-42f7-ac51-2327501c702f","expireTime":1719052952845}}
 */
let tokenInfo;

async function getToken(){
    let now = new Date().getTime();

    if(tokenInfo && tokenInfo.expireTime - now > 3600000){
        return tokenInfo.token;
    }
    let tokenUrl = 'http://cc.v-call.cn/api/token';
    let body = {
        "accessKeyId":"66d625a7-80b3-4578-a5ca-dc246fd0800c",
        "accessKeySecret":"16541037-169e-49d5-8d36-a3c07d99f31c"
    }
    let resp;
    try{
        resp = await axios.post(tokenUrl, body);
        tokenInfo = resp.data.data
        return getToken();
    }catch(err){
        console.log(resp)
    }
}

async function send(params){
    let serverUrl = 'http://cc.v-call.cn/openapi/message/flash/send';

    let reqData = {
        token: await getToken(),
        templateId: params.tplId,
        msgs:[{
            phone: params.mobile,
            userData: params.ext
        }]
    }
    let result = {}
    try{
        log.info('mt request to server:', reqData)
        let res = await axios.post(serverUrl, reqData);
        res = res.data;
        if(res.data.successes.length > 0){
            result.status = 1;
            result.mt_msg_id = res.data.successes[0].msgId;
            result.report_status = 0;
        }else{
            result.status = 2;
            result.mt_msg_id = res.data.errors[0].msgId;
            result.report_status = 2;
            result.report_desc = res.data.errors[0].msg;
            result.report_time = new Date();
        }
        log.info('mt response from server:', res.data)
    }catch(err){
        log.error('mt server error:', err.message)
        console.log(err)
        result.status = 2;
        result.report_status = 2;
        result.report_desc = 'CHN_ERR'
        result.report_time = new Date();
    }finally {
        result.send_time = new Date();
        try{
            let r = await models.mtMsg.findByIdAndUpdate(params._id, {$set: result});
            //r = update success number
        }catch(e1){
            log.error('update submit resp err', e1.message)
        }
    }
}

module.exports = { send }
